<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col
          ><el-button type="primary" @click="addDialogRoles"
            >添加角色</el-button
          ></el-col
        >
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="roleList">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="['bdbottom', i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini "
              @click="editeRole(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-sitting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <el-form
        :model="addRuleForm"
        :rules="addRules"
        ref="addRuleRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRuleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRuleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="addRules"
        ref="editRuleRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色ID">
          <el-input v-model="editForm.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有衣服的列表数据
      roleList: [],
      // 显示与隐藏添加角色的对话框
      addDialogVisible: false,
      //显示与隐藏角色修改对话框
      editDialogVisible: false,
      // 显示与隐藏分配权限对话框
      setRightDialogVisible: false,
      // 添加角色数据
      addRuleForm: {
        roleName: "",
        roleDesc: "",
      },
      // 根据id查询角色数据
      editForm: {},
      // 添加角色的规则验证
      addRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 8 个字符", trigger: "blur" },
        ],
      },
      //权限数据列表
      rightsList: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 默认选择节点的id值
      defKeys:[],
      //选中角色的id
      roleId:''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取所有角色的列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取用户角色失败");
      this.roleList = res.data;
    },
    //显示和隐藏添加角色的对话框
    addDialogRoles() {
      this.addDialogVisible = true;
    },
    // 添加角色
    addRoles() {
      this.$refs.addRuleRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.addRuleForm);
        console.log(res);
        if (res.meta.status !== 201) return this.$message.error("添加角色失败");
        this.$message.success("添加用户成功");
        this.addDialogVisible = false;
        this.getRolesList();
      });
    },
    //关闭添加用户对话框事件
    addDialogClose() {
      this.$refs.addRuleRef.resetFields();
    },
    //删除角色
    async deleteRole(id) {
      //弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmResult);
      //如果用户确定删除返回字符串 confirm 用户取消了删除则返回值为cancel
      if (confirmResult !== "confirm")
        return this.$message.error("已经取消删除");
      const { data: res } = await this.$http.delete(`roles/${id}`);
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("删除角色失败");
      this.$message.success("删除角色成功");
      this.getRolesList();
    },
    //显示修改对话框和根据id查询角色数据
    async editeRole(id) {
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get(`roles/${id}`);
      if (res.meta.status !== 200) return this.$message.error("获取用户失败");
      this.editForm = res.data;
    },
    //修改用户
    editRole() {
      this.$refs.editRuleRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        );
        if (res.meta.status !== 200) return this.$message.error("修改用户失败");
        this.$message.success("修改用户成功");
        this.getRolesList();
      });
    },
    // 监听修改对话框关闭事件
    editDialogClose() {
      this.$refs.editRuleRef.resetFields();
    },
    //根据id删除对应的权限
    async removeRightById(role, rightId) {
      //弹框提示用户是否删除
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result !== "confirm") return this.$message.error("取消删除");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) return this.$message.errror("删除权限失败");
      role.children = res.data;
    },
    //展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id;
      //获取所有权限的数据
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200)
        return this.$message.error("获取权限数据失败");
      this.rightsList = res.data;
      console.log(role);
      // 递归获取三级节点的id
      this.getLeafkeys(role,this.defKeys);
      console.log(this.defKeys);
      this.setRightDialogVisible = true;
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed(){
      this.defKeys = [];
    },  
    //通过递归的形式获取角色下所有的三级权限的id，并保存defKeys中
    getLeafkeys(node,arr){
      // 如果当前node节点不包括children属性，则是三级节点
      if(!node.children){
        return arr.push(node.id);
      }
      node.children.forEach(item => this.getLeafkeys(item , arr));
    },
    //点击为角色分配权限
    async allotRights(){
      const keys = [
        //若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
       ...this.$refs.treeRef.getCheckedKeys(),
       //若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点所组成的数组
       ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      // 数组变成数字拼接的字符串
      const idstr = keys.join(',');
      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idstr});
      if(res.meta.status !== 200) return this.$message.error('分配权限失败');
      this.$message.success('分配权限成功');
      this.getRolesList();
      this.setRightDialogVisible = false;
    }
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>